"""
设备查询服务
"""

from typing import List
import httpx

from app.config.settings import settings
from app.models.device import DeviceInfo
from app.utils.logger import get_logger

logger = get_logger(__name__)

# 内置 Mock 设备数据（当 settings.use_mock_devices=True 时启用）
MOCK_DEVICES: List[DeviceInfo] = [
    DeviceInfo(
        device_no="20250822-A411-101",
        device_name="411-照明-1",
        device_type="照明",
        place_id="P-4-411",
        place_name="4#411",
    ),
    DeviceInfo(
        device_no="20250822-A411-102",
        device_name="411-照明-2",
        device_type="照明",
        place_id="P-4-411",
        place_name="4#411",
    ),
    DeviceInfo(
        device_no="20250822-A411-100",
        device_name="411-照明-3",
        device_type="照明",
        place_id="P-4-411",
        place_name="4#411",
    ),
]

async def get_device_list(
    device_type: str = "", place_name: str = "", state: str = ""
) -> List[DeviceInfo]:
    """通过 HTTP GET 请求获取设备列表

    参数：
        device_type: 设备类型
        place_name: 场地名称
        state: 设备状态

    返回：
        设备信息列表
    """
    try:
        # 如果开启 Mock，则从内置列表中过滤返回
        if settings.use_mock_devices:
            logger.info("使用 Mock 设备数据进行查询")
            devices = MOCK_DEVICES
            return devices

        # 构建查询参数
        params = {"isPhysics": 0, "isShow": 1}
        if device_type:
            params["deviceType"] = device_type
        if place_name:
            params["placeName"] = place_name
        if state:
            params["stateDesc"] = state

        # 发送 HTTP GET 请求到设备服务
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"http://{settings.device_svc_host}:{settings.device_svc_port}/xbiotSys/iot/device/list",
                params=params,
            )
            response.raise_for_status()

            # 解析响应数据
            data = response.json()
            devices = []

            for device_data in data.get("data", []):
                device = DeviceInfo(
                    device_no=device_data["deviceNo"],
                    device_name=device_data["name"],
                    device_type=device_data["deviceType"],
                    place_id=device_data["placeId"],
                    place_name=device_data["place"],
                    is_physics=device_data.get("isPhysics", 0),
                    is_show=device_data.get("isShow", 1),
                    state=device_data.get("stateDesc", ""),
                )
                devices.append(device)

            return devices

    except Exception as e:
        print(f"获取设备列表失败: {e}")
        return []


async def control_device(device_nos: List[str] = [], state: str = "") -> List[str]:
    """通过 HTTP POST 请求控制设备

    参数：
        device_nos: 设备编号列表
        state: 目标状态

    返回：
        控制结果列表，包含成功或失败的信息
    """
    if not device_nos:
        return ["❌ 设备编号列表不能为空"]

    if not state:
        return ["❌ 目标状态不能为空"]

    results = []

    try:
        # 如果开启 Mock，则更新内存中的设备状态
        if settings.use_mock_devices:
            updated = 0
            for device_no in device_nos:
                for dev in MOCK_DEVICES:
                    if dev.device_no == device_no:
                        dev.state = state
                        updated += 1
                        break
            if updated > 0:
                results.append(f"✅  控制请求调用成功 - {state}")
            else:
                results.append("❌ 未找到匹配的设备编号")
            return results

        async with httpx.AsyncClient(timeout=30.0) as client:
            try:
                # 构建控制请求数据
                control_data = {
                    "deviceNos": device_nos,
                    "state": state,
                }

                # 发送 HTTP POST 请求到设备控制服务
                response = await client.post(
                    f"http://{settings.device_svc_host}:{settings.device_svc_port}/xbiotSys/iot/device/control/llm",
                    json=control_data,
                    headers={
                        "Content-Type": "application/json",
                        "User-Agent": "IoT-MCP-Server/1.0.0",
                    },
                )

                if response.status_code == 200:
                    data = response.json()
                    logger.info(f"控制请求结果: {data}")
                    if data.get("code") == 200:
                        results.append(f"✅  控制请求调用成功 - {state}")
                    else:
                        results.append(f"❌ 控制请求调用失败 - {data.get('msg')}")
                else:
                    results.append(f"❌ HTTP请求失败 - {response.status_code} {response.text}")

            except httpx.RequestError as e:
                results.append(f"❌ 网络请求错误 - {e}")
            except Exception as e:
                results.append(f"❌ 控制异常 - {e}")

    except Exception as e:
        results.append(f"❌ 设备控制服务连接失败: {e}")

    return results
